from django.db import models
from django.db.models import QuerySet

from common.constants import LEN_LONG
from application import settings


class Base(models.Model):
    """基础模型"""
    created_at = models.DateTimeField("创建时间", auto_now_add=True)
    updated_at = models.DateTimeField("更新时间", auto_now=True)

    class Meta:
        abstract = True


class CoreModel(models.Model):
    """
    标准抽象模型，可直接继承使用
    增加审计字段, 覆盖字段时, 字段名称请勿修改, 必须统一审计字段名称
    """
    id = models.BigAutoField(primary_key=True, help_text="Id", verbose_name="Id")
    description = models.CharField(max_length=LEN_LONG, verbose_name="描述", null=True, blank=True, help_text="描述")
    creator = models.ForeignKey(to=settings.AUTH_USER_MODEL, related_query_name='creator_query', null=True,
                                verbose_name='创建人', help_text="创建人", on_delete=models.SET_NULL,
                                db_constraint=False)
    modifier = models.CharField(max_length=LEN_LONG, null=True, blank=True, help_text="修改人", verbose_name="修改人")
    dept_belong_id = models.CharField(max_length=255, help_text="数据归属部门", null=True, blank=True,
                                      verbose_name="数据归属部门")
    update_datetime = models.DateTimeField(auto_now=True, null=True, blank=True, help_text="修改时间",
                                           verbose_name="修改时间")
    create_datetime = models.DateTimeField(auto_now_add=True, null=True, blank=True, help_text="创建时间",
                                           verbose_name="创建时间")

    class Meta:
        abstract = True


class SoftDeleteModel(models.Model):
    """
    软删除模型，需要时继承
    使用delete()方法进行软删除，使用restore()方法恢复已删除的数据
    """
    is_deleted = models.BooleanField(verbose_name="是否软删除", help_text='是否软删除', default=False, db_index=True)

    class Meta:
        abstract = True

    def delete(self, using=None, keep_parents=False):
        """删除"""
        self.deleted = True
        self.save(using=using)

    def restore(self, using=None):
        """恢复"""
        self.deleted = False
        self.save(using=using)


class SoftDeleteManager(models.Manager):
    """
    软删除的 Manager,用于管理支持软删除的 model 类
    """

    def get_queryset(self):
        return QuerySet(self.model).exclude(is_deleted=True)
